//
//  NSString+ZCHelp.m
//  UniversalApp
//
//  Created by 凯朱 on 2019/6/1.
//  Copyright © 2019 徐阳. All rights reserved.
//

#import "NSString+ZCHelp.h"
#import "SEGSAMKeychain.h"
@implementation NSString (ZCHelp)
/**
 日期转成日期字符串 代替方法 +(NSString *)dateStringFromDate:(NSDate *)date formatStr:(NSString *)fomatterStr
 
 @param date 日期
 @param formatStr 格式
 @return 日期字符串
 */
+(NSString *)dateStrFromDate:(NSDate *)date formatStr:(NSString *)formatStr
{
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:formatStr];
    NSString *dateStr =  [format stringFromDate:date];
    return dateStr;
}

/**
 从bundle里面加载视图控制器
 
 @return 视图控制器实例
 */
-(UIViewController *)nibVCFromMainBundle{
    if (self == nil || self.length == 0) {
        return nil;
    }
    Class className = NSClassFromString(self);
    
    NSBundle *bundle = [NSBundle mainBundle];
    if (bundle == nil) {
        return [[UIViewController alloc] init];
    }
    id nibViewController = [[className alloc] initWithNibName:self bundle:bundle];
    return nibViewController;
}


/**
 计算富文本高度
 
 @param width 宽度
 @param font 字体大小
 @param lineSpace 行距
 @return 文本高度
 */
-(CGFloat)countHeightWithWidth:(CGFloat)width font:(UIFont *)font lineSpace:(CGFloat)lineSpace {
   
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:self];
    text.font = font;
    text.lineSpacing = lineSpace;
    
    NSMutableParagraphStyle  *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.lineSpacing = lineSpace;
    text.paragraphStyle = paragraphStyle;
    
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:text];
    CGFloat reHeight = layout.textBoundingRect.size.height;
    CGFloat siHeight = layout.textBoundingSize.height;
    //这里可能存在四舍五入时候去掉尾数的情况
    if (siHeight - reHeight < 0) {
        return siHeight + 1;
    }
    return siHeight;
}

/**
 任何对象转字符串 代替以下方法

 @param obj 对象
 @return 字符串
 */
+(NSString *)valueToString:(id)obj{
    
    if ([obj isEqual:nil]) {
        return [NSString string];
    }
    
    if ([obj isEqual:[NSNull null]]) {
        return [NSString string];
    }
    
    if ([obj isKindOfClass:[NSString class]]) {
        return obj;
    }
    
    if ([obj isKindOfClass:[NSNumber class]]) {
        return [NSString stringWithFormat:@"%@", obj];
    }
    
    return [NSString string];
}

-(NSAttributedString *)htmlToAttributeWith:(NSDictionary *)options{
    NSData *data = [self dataUsingEncoding:NSUnicodeStringEncoding];
    NSMutableDictionary *newOptions = [[NSMutableDictionary alloc] initWithDictionary:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}];
    [newOptions addEntriesFromDictionary:options];
    NSAttributedString *html = [[NSAttributedString alloc]initWithData:data
                                                               options:newOptions
                                                    documentAttributes:nil
                                                                 error:nil];
    return html;
}


+(NSString *)stringNoUTCDateByFormatString:(NSString *)formatString date:(NSDate *)date
{
    static  NSDateFormatter * dateFromatter = nil;
    NSString * strDate = nil;
    if(!dateFromatter)
    {
        dateFromatter = [[NSDateFormatter alloc] init];
        [dateFromatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    }
    
    if (date == nil) return @"";
    
    @synchronized(dateFromatter)
    {
        if(formatString!=nil)
        {
            [dateFromatter setDateFormat:formatString];
        }
        strDate = [dateFromatter stringFromDate:date];
    }
    return strDate;
}

/*
 任何对象转字符串并且为空的时候用replaceStr代替
 */
+(NSString *)replaceWithString:(id)obj replaceStr:(NSString *)replaceStr{
    NSString *valueStr = [self valueToString:obj];
    replaceStr = [self valueToString:replaceStr];
    if (valueStr.length == 0) {
        if (replaceStr.length > 0) {
            valueStr = replaceStr;
        }
    }
    return valueStr;
}

-(UIViewController *)nibVCFromBundle{
    if (self == nil || self.length == 0) {
        return nil;
    }
    Class className = NSClassFromString(self);
    id nibViewController = [[className alloc] initWithNibName:self bundle:[NSBundle mainBundle]];
    return nibViewController;
}

#pragma 正则匹配手机号
-(BOOL)isTelNumber
{
    if (self.length == 0) {
        return NO;
    }
    NSString *pattern = @"^1+[3578]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}

/**
 是6位数字
 */
-(BOOL)isSixNumber{
   
    NSString *pattern = @"^[0-9]{6}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}


+(NSString *)timeStringFromTimestamp:(NSString *)timestamp formart:(NSString *)formart{
    // 创建 NSDate 对象
    NSTimeInterval tmes = [timestamp integerValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:tmes];
    
    // 创建日期格式化器
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formart];
    
    // 转换日期为字符串
    NSString *timeString = [dateFormatter stringFromDate:date];
    return timeString;
}

//将yyyy-MM-dd HH:mm:ss格式字符串转成指定格式字符串
+(NSString *)convertDateString:(NSString *)dateString outFormart:(NSString *)outFormart{
    // 创建日期格式化器
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    // 将字符串转换为 NSDate
    NSDate *date = [inputFormatter dateFromString:dateString];
    
    // 创建目标格式的日期格式化器
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:outFormart];
    
    // 将 NSDate 转换为目标格式字符串
    NSString *formattedDateString = [outputFormatter stringFromDate:date];
    return formattedDateString;
}

+(NSString *)convertDateString:(NSString *)dateString{
    // 创建日期格式化器
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    // 将字符串转换为 NSDate
    NSDate *date = [inputFormatter dateFromString:dateString];
    
    // 创建目标格式的日期格式化器
    NSString *outFormart = @"MMM.dd,yyyy";
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:outFormart];
    
    // 将 NSDate 转换为目标格式字符串
    NSString *formattedDateString = [outputFormatter stringFromDate:date];
    return formattedDateString;
}

-(BOOL)checkPassword{
//    return YES;
    if ([self isEqualToString:@"aaaaaaaa"] || [self isEqualToString:@"123456"]) {
        return YES;
    }
    if (self.length == 0) {
        return NO;
    }
    NSString *pattern = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[,.!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|<>/?]).{8,}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:self];
    if (isMatch == NO) {
        kShowToast(@"Password at least 8 characters, including uppercase and special characters");
    }
    
    return isMatch;
}

/**
 获取设备唯一UUID标识
 
 @return UUID字符串
 */
+(NSString *)getUniqueDeviceIdentifierAsString{
    NSString *uuidKey = @"AtliDeviceUUIDKey";
    NSString *uuidStr = kSTRING([[NSUserDefaults standardUserDefaults] valueForKey:@"checkUserUUID"]);//开发者模式下的uuid
    if (uuidStr.length > 0) {
        return uuidStr;
    }
    
    //1.取本地缓存里面的UUID
    NSString *uuid = [[NSUserDefaults standardUserDefaults] valueForKey:uuidKey];
    if (uuid) {
        return uuid;
    }
    
    //2.如果本地缓存没有，直接去钥匙串里面的UUID
    NSString *appName=[[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey];
    NSString *strApplicationUUID =  [SEGSAMKeychain passwordForService:appName account:@"incoding"];
    if (strApplicationUUID) {
        [[NSUserDefaults standardUserDefaults] setObject:strApplicationUUID forKey:uuidKey];
        return strApplicationUUID;
    }
    
    //3.本地和钥匙串里面都没有数据时 重新生成一个UUID - 保存到本地和钥匙串
    strApplicationUUID  = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSError *error = nil;
    SEGSAMKeychainQuery *query = [[SEGSAMKeychainQuery alloc] init];
    query.service = appName;
    query.account = @"incoding";
    query.password = strApplicationUUID;
    query.synchronizationMode = SAMKeychainQuerySynchronizationModeNo;
    if ([query save:&error]) {
        [[NSUserDefaults standardUserDefaults] setObject:strApplicationUUID forKey:uuidKey];
    }
    
    return strApplicationUUID;
}

- (BOOL)isValidEmail{
    if (self.length == 0) {
        return NO; // 空字符串不是有效的邮箱
    }
    
    // 正则表达式用于邮箱验证
    NSString *emailRegex = @"^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
    NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailPredicate evaluateWithObject:self];
}

/**
 URL编码
 
 @return 编码后的字符串
 */
-(NSString *)urlEncode
{
    return [self urlEncodeUsingEncoding:NSUTF8StringEncoding];
}

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding
{
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                 NULL,
                                                                                 (__bridge CFStringRef)self,
                                                                                 NULL,
                                                                                 (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                 CFStringConvertNSStringEncodingToEncoding(encoding)));
}

// 字符串转16进制字符串
- (NSString *)stringToHex {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableString *hex = [NSMutableString string];
    
    for (NSUInteger i = 0; i < data.length; i++) {
        [hex appendFormat:@"%02x", ((const uint8_t *)data.bytes)[i]];
    }
    
    return [hex copy];
}

/**
 * 传入参数与url，拼接为一个带参数的url 加入平台参数
 **/
+(NSString *)connectUrl:(NSDictionary *)params url:(NSString *)urlLink{
    
    if (![urlLink containsString:@"?"]) {
        NSString *str = @"";
        urlLink = [NSString stringWithFormat:@"%@?",urlLink];
        for(id key in params) {
            str = [str stringByAppendingString:[key urlEncode]];
            str = [str stringByAppendingString:@"="];
            str = [str stringByAppendingString:[[params objectForKey:key] urlEncode]];
            str = [str stringByAppendingString:@"&"];
        }
        if (str.length > 1) {
            // 去掉末尾的&
            str = [str substringToIndex:str.length - 1];
            // 返回含参url
            return [urlLink stringByAppendingString:str];
        }
    }
    else{
        // 初始化参数变量
        NSString *str = @"&";
        
        // 快速遍历参数数组
        for(id key in params) {
            str = [str stringByAppendingString:[key urlEncode]];
            str = [str stringByAppendingString:@"="];
            str = [str stringByAppendingString:[[params objectForKey:key] urlEncode]];
            str = [str stringByAppendingString:@"&"];
        }
        // 处理多余的&以及返回含参url
        if (str.length > 1) {
            // 去掉末尾的&
            str = [str substringToIndex:str.length - 1];
            // 返回含参url
            return [urlLink stringByAppendingString:str];
        }
        return nil;
    }
    return nil;
}

@end
